import { computed } from 'vue'
import { defineStore } from 'pinia'
import { useInfinite } from '@/compositions/request/infinite'
import API from '@/http'

export const useFollowStore = defineStore('follow', () => {
  const {
    dataList: creatorList,
    refresh: creatorRefresh,
    nextPage: creatorNextPage,
    reset: creatorReset,
  } = useInfinite({ request: API.Home.getForyouCreators })

  const followFetcher = useInfinite({ request: API.Media.getFollowList, onInit: onFollowData })
  const { refresh: feedRefresh, reset: feedReset } = followFetcher

  const noFollowAnyone = computed(() => creatorList.value.length !== 0)

  function init(viewerRouter) {
    viewerRouter.setFromMainViewer({ foryou: followFetcher })
  }

  function onFollowData(data) {
    if (data.length === 0) {
      creatorRefresh()
    } else {
      creatorReset()
    }
  }

  function refresh(isLogin = false) {
    if (isLogin) {
      feedRefresh({}, onFollowData)
    } else {
      creatorRefresh()
      feedReset()
    }
  }

  return {
    noFollowAnyone,
    creatorList,
    creatorNextPage,
    init,
    refresh,
  }
})
